package com.classba.udf;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class IpInfoUDF {
    static Double EARTH_RADIUS = 6378.137;
    static String[] fields = "ip,address,province_name,city_name,area_name,lng,lat".split(",");

    static class IpInfoDetail extends UDF {

        public Text evaluate(String ip) {
            String s = ipAnalysis(ip);
            return new Text(s);
        }
    }

    public static String getSign(String ip) {

        String app_id = "68007099";
        String app_key = "yZ25CylATmkQfrjp";
        String ts = String.valueOf(System.currentTimeMillis());
        String rand = "abcd";
        String sign = DigestUtils.md5Hex("app_id=" + app_id + "&ip=" + ip + "&rand=" + rand + "&timestamp=" + ts + app_key);


        String url = "http://api.xplusedu.com/account/currency/getRegionInfoByIp?app_id=" + app_id +
                "&ip=" + ip +
                "&rand=" + rand +
                "&timestamp=" + ts +
                "&sign=" + sign;
        return url;
    }


    public static String ipAnalysis(String ip) {
        JSONObject json = new JSONObject();
        try {
            URL url = new URL(getSign(ip));
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConn.getInputStream();
            String s = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            inputStream.close();
            JSONObject jsonObject = new JSONObject(s);
            int code = jsonObject.getInt("code");
            if (code == 200) {
                JSONObject dataObject = jsonObject.getJSONObject("data");
                for (String f : fields) {
                    String v = dataObject.getString(f);
                    json.put(f, v);
                }
                json.put("ip", ip);
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
}
